#pragma once

#include "Comm.hpp"

std::unordered_map<int, std::string> _statu_msg = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};

class Util
{
private:
    static char HEX_TO_DEC(char c)
    {
        if (isdigit(c)) return c - '0';
        else if (isupper(c)) return c - 'A' + 10;
        else if (islower(c)) return c - 'a' + 10;
        else LOG(WARNING, "Util::UrlDecode URL Formatting error!\n");
        return -1;
    }

public:
    // 字符串分割（按照 sep 对 src 进行分割）
    static size_t Split(const std::string &src, const std::string &sep, std::vector<std::string> *arr)
    {
        size_t offset = 0;
        while (offset < src.size())
        {
            size_t pos = src.find(sep, offset);
            if (pos == std::string::npos)
            {
                arr->push_back(src.substr(offset));
                return arr->size();
            }
            if (pos != offset)
                arr->push_back(src.substr(offset, pos - offset));
            offset = pos + sep.size();
        }
        return arr->size();
    }

    // 读取文件的所有内容，将读取的内容放进 Buffer 中
    static bool ReadFile(const std::string& file_name, std::string* content)
    {
        std::ifstream ifs(file_name, std::ios::binary);
        if (ifs.is_open() == false)
        {
            LOG(ERROR, "Util::ReadFile Failed to open file %s, errno: %d -> %s\n", file_name.c_str(), errno, strerror(errno));
            return false;
        }
        LOG(HDEBUG, "Util::ReadFile open file %s success\n", file_name.c_str());
        ifs.seekg(0, ifs.end);
        size_t file_size = ifs.tellg();
        ifs.seekg(0, ifs.beg);

        content->resize(file_size);
        ifs.read(&((*content)[0]), file_size);
        if (ifs.good() == false)
        {
            LOG(ERROR, "Util::ReadFile Failed to read from file %s, errno: %d -> %s\n", file_name.c_str(), errno, strerror(errno));
            ifs.close();
            return false;
        }
        LOG(HDEBUG, "Util::ReadFile read from file %s success\n", file_name.c_str());
        ifs.close();
        return true;
    }

    // 向文件中写入数据
    static bool WriteFile(const std::string& file_name, const std::string& content)
    {
        std::ofstream ofs(file_name, std::ios::binary | std::ios::trunc);
        if (ofs.is_open() == false)
        {
            LOG(ERROR, "Util::WriteFile Failed to open file %s, errno: %d -> %s\n", file_name.c_str(), errno, strerror(errno));
            return false;
        }
        LOG(HDEBUG, "Util::WriteFile open file %s success\n", file_name.c_str());

        ofs.write(content.c_str(), content.size());
        if (ofs.good() == false)
        {
            LOG(ERROR, "Util::WriteFile Failed to write into file %s, errno: %d -> %s\n", file_name.c_str(), errno, strerror(errno));
            ofs.close();
            return false;
        }
        ofs.close();
        LOG(HDEBUG, "Util::ReadFile write into file %s success\n", file_name.c_str());
        return true;
    }

    // URL 编码：避免 URL 中资源路径于查询字符串中的特殊字符于 HTTP 请求中特殊字符产生歧义 
    // 编码格式：将特殊字符的 ASCII 码值，转换为两个 16 进制字符 C++ -> C%2B%2B 
    // RFC3986 文档规定不编码的特殊字符为： . - _ ~ 以及字母和数字 
    // 但是在 W3C 文档规定：param（查询字符串）中的空格必须被编码为 +
    static std::string UrlEncode(const std::string url, bool convert_space_to_plus)
    {
        std::string res;
        for (auto& c : url)
        {
            if (isalnum(c) || c == '-' || c == '_' || c == '~' || c == '.')
            {
                res += c;
                continue;
            }
            else if (c == ' ' && convert_space_to_plus)
            {
                res += '+';
                continue;
            }
            else
            {
                // 转换为 %HH 格式 
                char tmp[4] = { 0 };
                snprintf(tmp, sizeof tmp, "%%%02X", c);
                res += tmp;
            }
        }
        return res;
    }

    // URL 解码
    static std::string UrlDecode(const std::string url, bool convert_plus_to_space)
    {
        std::string res;
        for (int i = 0; i < url.size(); ++i)
        {
            if (url[i] == '%' && (i + 2) < url.size())
            {
                unsigned char v1 = HEX_TO_DEC(url[i + 1]);
                unsigned char v2 = HEX_TO_DEC(url[i + 2]);
                res += (v1 * 16 + v2);
                i += 2;
            }
            else if (isalnum(url[i]) || url[i] == '-' || url[i] == '_' || url[i] == '~' || url[i] == '.')
            {
                res += url[i];
                continue;
            }
            else if (url[i] == '+' && convert_plus_to_space)
            {
                res += ' ';
                continue;
            }
            else
            {
                res += url[i];
            }
        }
        return res;
    }

    // 获取状态码描述
    static std::string GetStatuDesc(int statu)
    {
        auto it = _statu_msg.find(statu);
        if (it != _statu_msg.end())
        {
            return it->second;
        }
        return "UNKNOW";
    }

    // 根据文件后缀名获取 mime
    static std::string GetExtMime(const std::string& file_name)
    {
        size_t pos = file_name.find_last_of(".");
        if (pos == std::string::npos) { return "application/octet-stream"; }
        auto it = _mime_msg.find(file_name.substr(pos));
        if (it == _mime_msg.end()) { return "application/octet-stream"; }
        return it->second;
    }

    // 判断一个文件是否是目录
    static bool IsDirectory(const std::string& file_name)
    {
        struct stat st;
        int ret = ::stat(file_name.c_str(), &st);
        if (ret < 0)
        {
            LOG(ERROR, "Util::IsDirectory Get file %s properties error: %d -> %s", file_name.c_str(), errno, strerror(errno));
            return false;
        }
        return S_ISDIR(st.st_mode);
    }

    // 判断一个文件是否是普通文件
    static bool IsRegular(const std::string& file_name)
    {
        struct stat st;
        int ret = ::stat(file_name.c_str(), &st);
        if (ret < 0)
        {
            LOG(HDEBUG, "Util::IsRegular Get file %s properties error: %d -> %s\n", file_name.c_str(), errno, strerror(errno));
            return false;
        }
        return S_ISREG(st.st_mode);
    }

    // HTTP 请求的资源路径的有效性判断 
    // 利用相对于资源根目录的深度来判断，如果深度为负，则代表资源路径不合法 
    static bool IsValidPath(const std::string& path)
    {
        int level = 0;
        std::vector<std::string> arr;
        int ret = Split(path, "/", &arr);
        for (auto& e : arr)
        {
            if (e == "..") --level;
            else if (e == ".") continue;
            else ++level;
            if (level < 0) return false;
        }
        return true;
    }
};
